//
//  MealViewController.m
//  Restaurant
//
//  Created by wanghuan on 15/4/22.
//  Copyright (c) 2015年 wanghuan. All rights reserved.
//

#import "MealViewController.h"

@interface MealViewController () {

    UIButton *_shopNumBtn;

}

@end

@implementation MealViewController

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BackFromOrdersViewController) name:NSLocalizedString(@"BackFromOrdersViewController", nil) object:nil];
    
    

}

#pragma mark - 这是从OrdersViewController试图返回过来的
- (void)BackFromOrdersViewController {

    for (int i = 0; i < _tableArr.count; i++) {
        MealTableModel *model = _tableArr[i];
        
        model.amount = NSLocalizedString(@"0", nil);
    }
    
    self.priceLabel.text = NSLocalizedString(@"0", nil);
    
    [_shopArr removeAllObjects];
    
    [self createShopNumBtn];
    
    [_MyTableView reloadData];
    [_shopTableView reloadData];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [SavaMerchantId ShareMerchantId].merchantId = self.merchantId;
    
    
    self.view.backgroundColor = AppBackGroundColor;
    
    _shopArr = [[NSMutableArray alloc]init];
    _tableArr = [[NSMutableArray alloc]init];
    _numberArr = [[NSMutableArray alloc]init];
    
    _request = [[WHAFHTTPRequest alloc]init];
    
    self.navigationController.navigationBar.translucent = NO;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, APPWith, APPHeight-64-49)];
    view.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
    
    _request.Sblock = ^(id obj) {
    
        [self downLoad:obj];
        
        [view removeFromSuperview];
    
    };
    
    _request.Fblock = ^(NSString *error) {
    
        [self.view addSubview:view];
        
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络异常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alter show];
    
    };
    
    
     [_request createWHAFHttpRequestUrl:[NSString stringWithFormat:MealGetUrl,[SavaMerchantId ShareMerchantId].merchantId]];
    
//    
//    NSArray *nameArr = @[@"回锅肉",@"龙井虾仁",@"糖醋鲤鱼"];
//    NSArray *imageArr = @[@"huiguorou.png",@"longjingxiaren",@"tangculiyu.png"];
//    NSArray *briefArr = @[@"回锅肉是汉族特色菜肴。属中国八大菜系川菜中一种烹调猪肉的传统菜式，川西成都一带称作熬锅肉，川东重庆一带称为回锅肉。",@"龙井虾仁，是配以龙井茶的嫩芽烹制而成的虾仁，是富有浙江杭州地方特色的汉族名菜。",@"糖醋鲤鱼是山东省经典的汉族名菜之一，属于鲁菜系。据说“糖醋鲤鱼”最早始于黄河重镇——泺口镇。"];
//    for (int i = 0; i < 3; i++) {
//        MealTableModel *model = [[MealTableModel alloc]init];
//        
//        model.Title = nameArr[i];
//        model.MarketPrice = @"99.0";
//        model.amount = @"0";
//        model.Id = [NSString stringWithFormat:@"%d",i];
//        model.brief = briefArr[i];
//        model.ImageUrl = imageArr[i];
//        [_numberArr addObject:model.amount];
//        [_tableArr addObject:model];
//    }

    
    
    self.shopBtn.alpha = 1.0;
    
    self.certainBtn.layer.cornerRadius = 3;
    
    _MyTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, APPWith, APPHeight-64) style:UITableViewStyleGrouped];
    
    _MyTableView.delegate = self;
    
    _MyTableView.dataSource = self;
    
    _MyTableView.backgroundColor = AppBackGroundColor;
    
    [self.view addSubview:_MyTableView];
    
    _shopTableView = [[ShopTableView alloc]initWithFrame:CGRectMake(0, APPHeight, APPWith,3*50+40)];
    _shopTableView.shopBtnSelected = self.shopBtn;
    
    [self.view bringSubviewToFront:self.bottomView];
    
    [self.view sendSubviewToBack:_MyTableView];
    
    [self.view insertSubview:_shopTableView belowSubview:_bottomView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ShopframeChange) name:@"ShopframeChange" object:nil];
    
    _shopTableView.AddBlock = ^(UIButton *sender) {
        
        [self addClick:sender];
        
    };
    
    _shopTableView.DelegateBlock = ^(UIButton *sender) {
        
        [self deleteClick:sender];
        
    };
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadData) name:@"pleasereloadData" object:nil];
    
    
    [self createShopNumBtn];
    
}

#pragma mark - 创建购物车的商品个数的按钮

- (void)createShopNumBtn {

    //创建购物车的商品个数的按钮
    
    if (!_shopNumBtn) {
        
          _shopNumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        
    }
    
    _shopNumBtn.frame = CGRectMake(20, -5, 22, 22);
    
    [_shopNumBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)[_shopArr count]] forState:UIControlStateNormal];
    
    _shopNumBtn.titleLabel.font = [UIFont boldSystemFontOfSize:11];
    
    _shopNumBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 2.5, 0, 0);
    
    [_shopNumBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_shopNumBtn setBackgroundImage:[UIImage imageNamed:@"k1"] forState:UIControlStateNormal];
    
    [self.shopBtn addSubview:_shopNumBtn];


}

#pragma mark - 解析数据
- (void)downLoad:(id)data {

    NSArray *TableArr = [data objectForKey:@"obj"];
    
    for (NSDictionary *dataDic in TableArr) {
        
        MealTableModel *model = [[MealTableModel alloc]init];
        
        model.title = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"title"]];
        
        model.marketprice = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"marketprice"]];
        model.merchantId = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"merchantId"]];
        
        model.productId = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"productId"]];
        
        model.productImg = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"productImg"]];
        
        model.productImg = [NSString stringWithFormat:@"%@%@",MealImageUrl,model.productImg];
        
        model.amount = @"0";
        
        [_numberArr addObject:model.amount];
        
        [_tableArr addObject:model];
        
    }
    
    [_MyTableView reloadData];
    
    

}

#pragma mark - pleasereloadData的监听事件
- (void)reloadData {
    
    _shopTableView.shopArr = _shopArr;
    
    [_shopNumBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)_shopArr.count] forState:UIControlStateNormal];
    
    [_shopTableView reloadData];
    
    [_MyTableView reloadData];

    
    
}

- (void)viewDidAppear:(BOOL)animated {

    [_shopTableView.cellArray removeAllObjects];
    
    [_shopTableView.DeleteArray removeAllObjects];
    
    [_shopNumBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)_shopArr.count] forState:UIControlStateNormal];
   
    [_shopTableView reloadData];

}

#pragma mark - _shopTableView的frame发生改变时
- (void)ShopframeChange {
 
       
    for (shoppingModel *Smodel in _shopTableView.DeleteArray) {
        
        int index = 0;
        
        for (MealTableModel *model in _tableArr) {
           
            if ([Smodel.productId isEqual:model.productId]) {
                model.amount = @"0";
        
                NSString *numStr = [_numberArr objectAtIndex:index];
                numStr = @"0";
                [_numberArr replaceObjectAtIndex:index withObject:numStr];
                
                
            }
            
            index++;
        }
    }
    
    [_MyTableView reloadData];

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 0.1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _tableArr.count;


}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 100;
    

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    float price = 0;
    
    MealTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqq"];
    
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"MealTableViewCell" owner:self options:nil].lastObject;
    }
    
    MealTableModel *model = [_tableArr objectAtIndex:indexPath.row];
    cell.nameLabel.text = model.title;
    cell.priceLabel.text = model.marketprice;
    cell.numLabel.text = model.amount;
//    cell.briefLabel.text = model.description;
    //    cell.imageView.backgroundColor = [UIColor yellowColor];
    
    [cell.CellImageView sd_setImageWithURL:[NSURL URLWithString:model.productImg] placeholderImage:nil];

    cell.deleteBtn.tag = indexPath.row;
    
    cell.addBtn.tag = indexPath.row;
    
    model.tag = indexPath.row;
    
    
    [cell.deleteBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.addBtn addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    UITapGestureRecognizer *cellTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mealDetailView:)];
    
    [cell.CellImageView addGestureRecognizer:cellTap];
    
    //当收拾添加进去 在设置tag值
    cellTap.view.tag = model.tag;
    
    cell.CellImageView.userInteractionEnabled = YES;
    
    for (int i = 0; i < _shopArr.count; i++) {
        
        shoppingModel *sm = [_shopArr objectAtIndex:i];
        
        price += [sm.prices floatValue]*[sm.number intValue];
        
        NSLog(@"%f,%d",[sm.prices floatValue],[sm.number intValue]);
        
    }
    
    //计算label的值
    self.priceLabel.text = [NSString stringWithFormat:@"%.1f",price];
    
    self.certainBtn.backgroundColor = [UIColor colorWithRed:231.0/255.0 green:67.0/255.0 blue:73.0/255.0 alpha:1];
    
    if ([self.priceLabel.text isEqual:@"0.0"]) {
        self.priceLabel.text = @"0";
        
        self.certainBtn.backgroundColor = [UIColor grayColor];
        
    }

    return cell;

}

#pragma mark - 头像点击事件
- (void)mealDetailView:(UITapGestureRecognizer *)cellTap {

    

    MealDetailViewController *mdvc = [[MealDetailViewController alloc]init];
    
    mdvc.shopArr = _shopArr;
    
    mdvc.priceStr = self.priceLabel.text;
    
    mdvc.numberArr = _numberArr;
    
    mdvc.tableArr = _tableArr;
    
    MealTableModel *model = [_tableArr objectAtIndex:cellTap.view.tag];
   
    mdvc.mealModel = model;
    
    
    [self.navigationController pushViewController:mdvc animated:YES];


}

#pragma mark - 增加选菜的数量
- (void)deleteClick:(UIButton *)sender {

    
    int number = [[_numberArr objectAtIndex:sender.tag] intValue];
    
   
    
    NSString *numStr = [_numberArr objectAtIndex:sender.tag];
    
    
    
    if (--number < 0) {
        return;
    }
    
    
    numStr = [NSString stringWithFormat:@"%d",number];
    [_numberArr replaceObjectAtIndex:sender.tag withObject:numStr];
    [self addModel:sender];
   
    
    
}

- (void)addClick:(UIButton *)sender {
    
    int number = [[_numberArr objectAtIndex:sender.tag] intValue];
    
   
    
    NSString *numStr = [_numberArr objectAtIndex:sender.tag];

    
    if (++number > 20) {
        return;
    }

    numStr = [NSString stringWithFormat:@"%d",number];
        
    [_numberArr replaceObjectAtIndex:sender.tag withObject:numStr];
    [self addModel:sender];
    
}



//在添加、删除数据
- (void)addModel:(UIButton *)sender {
    
     NSLog(@"%ld",(long)sender.tag);
    
    if (self.shopBtn.selected) {
        
        if (_shopArr.count < 3) {
            _shopTableView.frame = CGRectMake(0, APPHeight-_shopArr.count*50-40-49, APPWith,_shopArr.count*50+40);
        } else {
            
            _shopTableView.frame = CGRectMake(0, APPHeight-3*50-40-49, APPWith,3*50+40);
        }
    }

      
    NSString *numStr = [_numberArr objectAtIndex:sender.tag];
    
    MealTableModel *model = [_tableArr objectAtIndex:sender.tag];
    model.amount = numStr;
    
    for (shoppingModel *Smodel in _shopArr) {
        if ([Smodel.productId isEqual:model.productId]) {
           
            if (![numStr isEqual:@"0"]) {
                Smodel.number = model.amount;
               
                
            } else {
            
                [_shopArr removeObject:Smodel];
            }
             _shopTableView.shopArr = _shopArr;
            
            [_shopNumBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)_shopArr.count] forState:UIControlStateNormal];
            
            [_shopTableView reloadData];
            [_MyTableView reloadData];
            
            return;
            
        }
    }
    
    shoppingModel *Smodel = [[shoppingModel alloc]init];
    
    Smodel.nameStr = model.title;
    Smodel.prices = model.marketprice;
    Smodel.number = model.amount;
    Smodel.productId = model.productId;
    Smodel.tag = model.tag;
    
    [_shopArr addObject:Smodel];
    
    _shopTableView.shopArr = _shopArr;
    
    [_shopTableView.cellArray removeAllObjects];
    
    [_shopNumBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)_shopArr.count] forState:UIControlStateNormal];
    
    [_shopTableView reloadData];
    [_MyTableView reloadData];



}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)shopClick:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    [UIView animateWithDuration:1 animations:^{
        
        self.shopBtn.alpha = 0.0;
        if (_shopArr.count > 2) {
            _shopTableView.frame = CGRectMake(0, APPHeight-50*3-40-49, APPWith,50*3+40);
        } else {
        
            _shopTableView.frame = CGRectMake(0, APPHeight-50*_shopArr.count-40-49, APPWith,50*_shopArr.count+40);
        
        }
    }];
    
    
}

- (void)viewDidDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    
    self.loopDrawLine();
    
    
}
#pragma mark - “选好了”的按钮的点击事件
- (IBAction)certainClick:(UIButton *)sender {
    
    if(_shopArr.count) {
    
        OrdersViewController *ovc = [[OrdersViewController alloc]init];
        
        ovc.shopMutArray = _shopArr;
        
        ovc.price = self.priceLabel.text;
        
        ovc.tabBarController.tabBar.hidden = NO;
        
        [self.navigationController pushViewController:ovc animated:YES];
    
    }
}
- (IBAction)backClick:(UIButton *)sender {
    
//    ScanViewController *svc = [[ScanViewController alloc]init];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
@end
